/**
 * @desc: 组合预览
 * @author: fj
 */
import React, { useState, useEffect, useMemo } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import VList from '@/components/VirtualList';
import CommonImgsLoad from '@/components/CommonImgsLoad';
import CommonZjfImg from '@/components/CommonImg/ZifComponent';
import CommonSysImg from '@/components/CommonImg/SysComponent';
import CommonPlatImg from '@/components/CommonImg/PlatformComponent';
import BatchSetChannel from './BatchSetChannel';
import { cloneDeep, findIndex } from 'lodash';
import {
  Button,
  Checkbox,
  Select,
  Popover,
  message,
  Input,
  Popconfirm,
  Empty,
} from 'antd';
import { formatAmount } from '@/utils/utils.jsx';
import { queryTypeChannel } from '@/services/common';
import CommonTag from '@/components/CommonTag';
import Iconfont from '@/components/IconFont';
import { batchAddComposeGoods } from '../service';
import { getCurrentUser } from '@/utils/authority';
import styles from './GoodsList.module.less';

const { TextArea } = Input;
const { Option } = Select;

//获取渠道类型
const getChannelType = (arr) => {
  if (arr.length == 0) {
    return null;
  }
  const list = arr.map((v) => v.deliverType);
  if (list.includes(3)) {
    if (list.includes(4)) {
      return null;
    } else {
      //库存加拿货
      return 1;
    }
  } else {
    if ((list.includes(1) || list.includes(2)) && !list.includes(4)) {
      let btn = false;
      for (let i in arr) {
        if (arr[i].isCarefullySelected != 1) {
          btn = true;
          break;
        }
      }
      if (btn) {
        //都是严选商品
        return 8;
      } else {
        return 7;
      }
    } else {
      //都是供应商直发
      let btn = false;
      for (let i in arr) {
        if (arr[i].storeId != arr[0].storeId) {
          btn = true;
          break;
        }
      }
      if (btn) {
        return null;
      } else {
        //同一供应商的供应商直发
        return 0;
      }
    }
  }
};

//记录当前的type值，用以请求发货渠道；
let channelType;

const CombinPreview = ({ visible, listArr, handleCancel, handleOk }) => {
  const [combinList, setCombinList] = useState([]); //组合的规格商品数
  const [scrollIndex, setScrollIndex] = useState(undefined); //重复的时候滚动到当前index
  const [channelList, setChannelList] = useState([]);
  const [channelSwitch, setChannelSwitch] = useState(false); //批量设置渠道弹窗
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      setCombinList(listArr);
      channelType = null;
    }
  }, [visible]);

  const optionChannel = channelList.map((item) => {
    return (
      <Option key={item.id} value={item.id}>
        {item.channelName}
        {item.id == 0
          ? null
          : getCurrentUser().uuid == item.uuid
          ? '(自发)'
          : '(第三方)'}
      </Option>
    );
  });

  //获取渠道下拉列表
  const getChannelList = async (val) => {
    const type = getChannelType(val);
    if (type && channelType != type) {
      channelType = type;
      setLoading(true);
      const { data, success } = await queryTypeChannel({
        isDeleted: 0,
        type,
        uuid: getCurrentUser().uuid,
      });
      setLoading(false);
      if (success) {
        setChannelList(data);
      }
    } else {
      if (type == 0) {
        const arr = [{ id: 0, channelName: `${val[0].storeName}(直发)` }];
        setChannelList(arr);
      } else if (type == null) {
        setChannelList([]);
      }
    }
  };

  //获取渠道下拉列表
  const getChannelList2 = async (type, list) => {
    if (type && channelType != type) {
      channelType = type;
      setLoading(true);
      const { data, success } = await queryTypeChannel({
        isDeleted: 0,
        type,
        uuid: getCurrentUser().uuid,
      });
      setLoading(false);
      if (success) {
        setChannelList(data);
      }
    } else {
      if (type == 0) {
        const val = list.filter((item) => item.checked);
        const arr = [
          { id: 0, channelName: `${val[0].subGoodsArr[0].storeName}(直发)` },
        ];
        setChannelList(arr);
      } else if (type == null) {
        setChannelList([]);
      }
    }
  };

  //取消
  const onCancel = () => {
    handleCancel();
  };

  //处理subGoodsArr数据提交
  const hanldeSubGoodsArr = (arr) => {
    const newArr = [];
    arr.map((item) => {
      newArr.push({
        deliverType: item.deliverType,
        goodsCommonId: item?.goodsCommonId,
        goodsId: item?.goodsId,
        goodsNum: item?.goodsNum,
        productId: item?.productId,
        productType: item?.productType,
        storeId: item?.storeId,
        type: item?.type,
      });
    });
    return newArr;
  };

  //子选项有勾选
  const indeterminate = useMemo(() => {
    if (
      combinList.some((item) => item.checked == true) &&
      combinList.some((item) => item.checked != true)
    ) {
      return true;
    }
    return false;
  }, [combinList]);

  //按钮全选状态
  const allChecked = useMemo(() => {
    if (combinList.every((item) => item.checked == true)) {
      return true;
    }
    return false;
  }, [combinList]);

  //渲染行信息
  const rowRender = ({ index, style }) => {
    const obj = combinList[index];
    const {
      composeName,
      code,
      composeImage,
      channelId,
      nameRepeat,
      codeRepeat,
      subGoodsArr = [],
      checked,
    } = obj;
    return (
      <div key={JSON.stringify(subGoodsArr)} className={styles.warp} style={{ ...style }}>
        <div
          style={{
            display: 'flex',
            // borderBottom: '1px solid #f0f0f0',
            padding: '12px',
            background: index == scrollIndex ? '#EBF4FF' : 'none',
          }}
        >
          <div className={`${styles.warpItemCenter} ${styles.w100}`}>
            <Checkbox
              checked={checked}
              onChange={(e) => handleSelect(e, index, obj)}
            />
          </div>
          <div className={`${styles.warpItemCenter} ${styles.w100}`}>
            {index + 1}
          </div>
          <div className={`${styles.w200}`}>
            <div className={`${styles.warpItem} ${styles.w200}`}>
              <span className={styles.labelReqire}>组合图：</span>
              <span style={{ width: '100px' }}>
                <CommonImgsLoad
                  img={composeImage ? composeImage : ''}
                  handleOk={(val) => handleDone(val, index, obj)}
                />
                {composeImage ? (
                  ''
                ) : (
                  <span className="common-color9">图片不能为空</span>
                )}
              </span>
            </div>
            <div className={`${styles.mb30} ${styles.w200}`}>
              <TextArea
                onChange={(e) => composeNameChange(e, index, obj)}
                value={composeName}
                showCount
                maxLength={60}
              />
              {composeName ? (
                ''
              ) : (
                <span className="common-color9">组合名称不能为空</span>
              )}
              {nameRepeat ? (
                <span className="common-color9">组合名称不能重复</span>
              ) : (
                ''
              )}
            </div>
            <div className={`${styles.warpItem} ${styles.w200}`}>
              <span style={{ width: '150px' }} className={styles.labelReqire}>
                组合编号：
              </span>
              <span>
                <div>
                  <Input
                    rows={1}
                    maxLength={50}
                    value={code}
                    style={{ width: '115px' }}
                    onChange={(e) => composeNoChange(e, index, obj)}
                  />
                </div>
                {code ? (
                  ''
                ) : (
                  <div className="common-color9">组合编号不能为空</div>
                )}
                {codeRepeat ? (
                  <span style={{ marginTop: '20px' }} className="common-color9">
                    组合编号已存在，不能重复
                  </span>
                ) : (
                  ''
                )}
              </span>
            </div>
          </div>
          <div
            className={`${styles.w400} ${styles.scrollX} ${styles.warpItemCenter}`}
          >
            {subGoodsArr.map((item, index) => {
              const newCode =
                item?.customType == 'sys'
                  ? item?.skuId
                  : item?.customType == 'shop'
                  ? item?.outStoreSku
                  : item?.goodsId;
              return (
                <div className={styles.mr15} key={index}>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    {item.customType == 'shop' && (
                      <div className={styles.w48}>
                        <CommonPlatImg img={item.ecGoodsImage} />
                      </div>
                    )}
                    {item.customType == 'sys' && (
                      <div className={styles.w48}>
                        <CommonSysImg
                          img={item.goodsImage}
                          isCloudIcon={item.isCarefullySelected}
                          storeId={item.storeId}
                        />
                      </div>
                    )}
                    {item.customType == 'zjf' && (
                      <div className={styles.w48}>
                        <CommonZjfImg
                          img={item.goodsImage}
                          isCloudIcon={item.isCarefullySelected}
                          storeId={item.storeId}
                        />
                      </div>
                    )}
                    <div
                      style={{
                        display: 'flex',
                        flexDirection: 'column',
                        flex: 1,
                        // width: '134px',
                        marginLeft: '8px',
                      }}
                    >
                      {item.customType == 'shop' && (
                        <>
                          <Popover
                            content={
                              <div style={{ width: '200px' }}>
                                <span>
                                  {`【${item?.storeName}】`}
                                  {item.ecGoodsName}
                                </span>
                                <span>{item.ecSkuName}</span>
                              </div>
                            }
                          >
                            <span className="textOverflowMultiTwo">
                              {`【${item?.storeName}】`}
                              {item.ecGoodsName}
                            </span>
                            <span className="textOverflowMultiTwo">
                              {item.ecSkuName}
                            </span>
                          </Popover>
                          <span className="common-color9">
                            ¥{formatAmount(item.ecGoodsPrice)}
                            <span className={styles.goodsNum}>
                              x{item.goodsNum}
                            </span>
                          </span>
                        </>
                      )}
                      {item.customType == 'sys' && (
                        <>
                          <Popover
                            content={
                              <div style={{ width: '200px' }}>
                                <span>
                                  {'【系统商品】'}
                                  {item.goodsName}
                                </span>
                                <span>{item.skuName}</span>
                              </div>
                            }
                          >
                            <span className="textOverflowMultiTwo">
                              {'【系统商品】'}
                              {item.goodsName}
                            </span>
                            <span className="textOverflowMultiTwo">
                              {item.skuName}
                            </span>
                          </Popover>
                          <span className="common-color9">
                            ¥{formatAmount(item.goodsPrice)}
                            <span className={styles.goodsNum}>
                              x{item.goodsNum}
                            </span>
                          </span>
                        </>
                      )}
                      {item.customType == 'zjf' && (
                        <>
                          <Popover
                            content={
                              <div style={{ width: '200px' }}>
                                <span>
                                  {`【${item?.storeName}】`}
                                  {item.goodsName}
                                </span>
                                <span>{item.goodsSpec}</span>
                              </div>
                            }
                          >
                            <span className="textOverflowMultiTwo">
                              {`【${item?.storeName}】`}
                              {item.goodsName}
                            </span>
                            <span className="textOverflowMultiTwo">
                              {item.goodsSpec}
                            </span>
                          </Popover>
                          <span className="common-color9">
                            ¥
                            {item.vipPrice
                              ? formatAmount(item.vipPrice)
                              : formatAmount(item.goodsPrice)}
                            <span className={styles.goodsNum}>
                              x{item.goodsNum}
                            </span>
                          </span>
                        </>
                      )}
                      <Popover
                        content={
                          <div>
                            <span>商品编码：</span>
                            <span>{newCode}</span>
                          </div>
                        }
                      >
                        <div className="textOverflowMultiOne">
                          <span>商品编码：</span>
                          <span>{newCode}</span>
                        </div>
                      </Popover>
                      <span>
                        {(item.deliverType == 1 || item.deliverType == 2) && (
                          <CommonTag type="nahuo" />
                        )}
                        {item.deliverType == 3 && <CommonTag type="zifa" />}
                        {item.deliverType == 4 && <CommonTag type="cjzf" />}
                      </span>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
          <div className={`${styles.warpItemCenter} ${styles.w200}`}>
            <div>
              <Select
                value={channelId}
                size="small"
                onDropdownVisibleChange={() => handleGetChannel(subGoodsArr)}
                onChange={(e) => handleChangeChannel(e, index, obj)}
                placeholder="请选择发货渠道"
                style={{ width: '140px' }}
              >
                {optionChannel}
              </Select>
              {channelId || channelId == '0' ? (
                ''
              ) : (
                <div className="common-color9">渠道不能为空</div>
              )}
            </div>
          </div>
          <div className={`${styles.warpItemCenter} ${styles.w100}`}>
            <span className="common-color9">{getCombinMoney(subGoodsArr)}</span>
          </div>
          <div className={`${styles.warpItemCenter} ${styles.w100}`}>
            <Popconfirm
              title="确定删除该组合?"
              onConfirm={() => handleDeleteGoods(index)}
              okText="确定"
              cancelText="取消"
            >
              <span className="opera-span-common">删除</span>
            </Popconfirm>
          </div>
        </div>
      </div>
    );
  };

  //点击选择行
  const handleSelect = (e, index, obj) => {
    const val = e.target.checked;
    // let arr = [];
    // if (val) {
    //   arr = [...selectRowKeys, id];
    // } else {
    //   arr = selectRowKeys.filter((v) => v != id);
    // }
    // setSelectRowKeys(arr);
    const arr = cloneDeep(combinList);
    obj.checked = val;
    arr.splice(index, 1, obj);
    setCombinList(arr);
  };

  //点击全选
  const onCheckAllChange = (e) => {
    const val = e.target.checked;
    const arr = cloneDeep(combinList);
    arr.map((item) => (item.checked = val));
    setCombinList(arr);
  };

  //设置第一个重复的项index
  const setRepeatIndex = (arr) => {
    let repeatIndex = -1;
    const codeRepeatIndex = findIndex(arr, ['codeRepeat', true]); //第一个名称重复的index
    const nameRepeatIndex = findIndex(arr, ['nameRepeat', true]); //第一个编码重复的index
    if (codeRepeatIndex > -1 || nameRepeatIndex > -1) {
      //存在编码和code重复的情况
      let repeatIndexArr = [codeRepeatIndex, nameRepeatIndex].filter(
        (z) => z >= 0
      );
      repeatIndex = Math.min.apply(null, repeatIndexArr); //找出重复最小的index
    }
    return repeatIndex;
  };

  //设置第一个为空的项的index
  const setEmptyIndex = (arr) => {
    let emptyIndex = -1;
    const nameIndex = findIndex(arr, ['composeName', '']); //第一个名称为空的index
    const composeImageIndex = findIndex(arr, ['composeImage', '']); //第一个图片为空的index
    const codeIndex = findIndex(arr, ['code', '']); //第一个编号为空的index
    const channelIndex = findIndex(arr, ['channelId', '']); //第一个渠道为空的index
    if (
      nameIndex > -1 ||
      composeImageIndex > -1 ||
      codeIndex > -1 ||
      channelIndex > -1
    ) {
      let IndexArr = [
        nameIndex,
        composeImageIndex,
        codeIndex,
        channelIndex,
      ].filter((z) => z >= 0);
      //存在未填的情况
      emptyIndex = Math.min.apply(null, IndexArr); //查找几个数中的最小的index
    }
    return emptyIndex;
  };

  //保存
  const onSave = async () => {
    const paramsArr = []; //最后提交的数据
    const arr = cloneDeep(combinList);
    let emptyIndex = setEmptyIndex(arr);
    if (emptyIndex >= 0) {
      //存在未填的情况
      setScrollIndex(emptyIndex);
    } else {
      //没有未填
      arr.forEach((item, index) => {
        let newArr = cloneDeep(arr); //不包含自己项的其他项
        newArr.splice(index, 1);
        let obj = item;
        obj.nameRepeat =
          findIndex(newArr, ['composeName', item.composeName]) > -1
            ? true
            : false; //与其他项比填写的名称是否重复
        obj.codeRepeat =
          findIndex(newArr, ['code', item.code]) > -1 ? true : false; //与其他项比填写的名称是否重复
        arr.splice(index, 1, obj); // 加上重复提示
      });
      let repeatIndex = setRepeatIndex(arr);
      if (repeatIndex > -1) {
        //存在填写重复的情况
        setCombinList(arr);
        setScrollIndex(repeatIndex);
      } else {
        //填写不重复请求后端数据
        arr.forEach((item) => {
          paramsArr.push({
            channelId: item.channelId,
            composeName: item.composeName,
            code: item.code,
            composeImage: item.composeImage,
            composePrice: getCombinMoney(item.subGoodsArr),
            goodsDtoS: hanldeSubGoodsArr(item.subGoodsArr),
          });
        });
        const { data = {}, success } = await batchAddComposeGoods(paramsArr);
        const { code = [], name = [] } = data;
        if (success) {
          if (code.length == 0 && name.length == 0) {
            message.success('提交成功');
            handleOk();
          } else {
            const codeIndex = [],
              nameIndex = []; //存在与数据库重复的名称和编号
            code.map((x) => {
              codeIndex.push(findIndex(paramsArr, ['code', x]));
            });
            name.map((y) => {
              nameIndex.push(findIndex(paramsArr, ['composeName', y]));
            });
            arr.forEach((item, index) => {
              let obj = item;
              obj.nameRepeat = nameIndex.includes(index) ? true : false; //与数据库中名称重复
              obj.codeRepeat = codeIndex.includes(index) ? true : false; //与数据库中编码重复
              arr.splice(index, 1, obj); // 加上重复提示
            });
            let repeatIndex = setRepeatIndex(arr);
            if (repeatIndex > -1) {
              //存在与数据库重复的情况
              setScrollIndex(repeatIndex);
              setCombinList(arr);
            }
          }
        }
      }
    }
  };

  //图片上传回调手动更新表单值
  const handleDone = (val, index, obj) => {
    const arr = cloneDeep(combinList);
    obj.composeImage = val == undefined ? '' : val;
    arr.splice(index, 1, obj);
    setCombinList(arr);
  };

  //获取渠道信息
  const handleGetChannel = (val) => {
    if (val) {
      getChannelList(val);
    }
  };

  //更改渠道信息
  const handleChangeChannel = (val, index, obj) => {
    const arr = cloneDeep(combinList);
    obj.channelId = val;
    arr.splice(index, 1, obj);
    setCombinList(arr);
  };

  //更改商品编号
  const composeNoChange = (e, index, obj) => {
    const arr = cloneDeep(combinList);
    obj.code = e.target.value;
    if (findIndex(arr, ['code', e.target.value]) == -1) {
      //更改的code不重复
      obj.codeRepeat = false;
    }
    arr.splice(index, 1, obj);
    setCombinList(arr);
  };

  //更改商品名称
  const composeNameChange = (e, index, obj) => {
    const arr = cloneDeep(combinList);
    obj.composeName = e.target.value;
    if (findIndex(arr, ['composeName', e.target.value]) == -1) {
      //更改的name不重复
      obj.nameRepeat = false;
    }
    arr.splice(index, 1, obj);
    setCombinList(arr);
  };

  //获取组合金额
  const getCombinMoney = (arr) => {
    let totalMoney = 0;
    arr.map((item) => {
      totalMoney = totalMoney + item?.goodsNum * item?.goodsPrice;
    });
    return totalMoney.toFixed(2);
  };

  //删除颜色规格
  const handleDeleteGoods = (index) => {
    const arr = cloneDeep(combinList);
    arr.splice(index, 1);
    setCombinList(arr);
  };

  //批量设置商品渠道
  const handleBatchSetChannel = () => {
    if (combinList.some((item) => item.checked == true)) {
      setChannelSwitch(true);
    } else {
      message.info('请勾选商品组合！');
    }
  };

  //批量设置渠道
  const BatchSetChannelProps = {
    channelSwitch,
    combinList,
    channelClose() {
      setChannelSwitch(false);
    },
    handleOk(arr, type) {
      getChannelList2(type, arr);
      setCombinList(arr);
      setChannelSwitch(false);
    },
  };

  const VListProps = {
    rowRender,
    rowHeight: 300,
    listHeight: 350,
    rowCount: combinList.length,
    scrollToIndex: scrollIndex,
    style: { overflowX: 'auto', width: '100%' },
  };

  return (
    <div>
      <CommonModal
        title={'组合预览'}
        visible={visible}
        onCancel={onCancel}
        width="1400px"
        overflowY="hidden"
        footer={[
          <Button key="back" onClick={onCancel}>
            上一步
          </Button>,
          <Button key="save" type="primary" onClick={onSave}>
            保存
          </Button>,
        ]}
      >
        <div className={`${styles.goodsTopic}`} style={{marginBottom:'6px'}}>
          <p>1.组合预览里如果有个别组合不需要，可以删除后再保存；</p>
          <p>
            2.每个组合都需要选择各自的发货渠道，如果发货渠道选项为空，说明组合里子商品的商品类型不支持生成组合；
          </p>
          <p>
            3.组合编号不能重复，如果网店商品编码与组合编号一致的，则会自动匹配（组合编号注意不要与{APP_TITLE}供应商商品编号一样）；
          </p>
          <p>4.保存后会批量生成多个组合，请仔细检查组合商品是否正确</p>
        </div>
        <div>
          <div className={styles.tableHeader}>
            <div className={`${styles.warpItem} ${styles.w100}`}>
              <Checkbox
                checked={allChecked}
                indeterminate={indeterminate}
                onChange={onCheckAllChange}
                className="allCheckedStyle"
              />
              &nbsp; 全选
            </div>
            <div className={`${styles.warpItem} ${styles.w100}`}>组合序号</div>
            <div className={`${styles.warpItem} ${styles.w200}`}>
              组合图片和名称
              <Popover
                content={
                  <div className={styles.w200}>
                    组合名称注意不要重复，以免后面选择时不知道对应哪个
                  </div>
                }
              >
                <div>
                  <Iconfont type="iconwenhao1" />
                </div>
              </Popover>
            </div>
            <div className={`${styles.warpItem} ${styles.w400}`}>子商品</div>
            <div className={`${styles.warpItem} ${styles.w200}`}>
              组合商品发货渠道
              <Popover
                content={
                  <div className={styles.w200}>
                    ①自发渠道：支持库存商品或拿货商品的组合
                    ②供应商直发渠道：只支持同一个供应商的供应商直发商品类型的组合
                    ③普通代发渠道：只支持无严选图标的拿货商品
                    ④严选代发渠道：只支持有严选图标的拿货商品
                  </div>
                }
              >
                <div>
                  <Iconfont type="iconwenhao1" />
                </div>
              </Popover>
            </div>
            <div className={`${styles.warpItem} ${styles.w100}`}>组合金额</div>
            <div className={`${styles.warpItem} ${styles.w100}`}>
              操作
              <Popover
                content={
                  <div className={styles.w200}>不需要的组合删除后不会创建</div>
                }
              >
                <div>
                  <Iconfont type="iconwenhao1" />
                </div>
              </Popover>
            </div>
          </div>
          <div style={{ marginBottom: '20px' }}>
            <Button onClick={() => handleBatchSetChannel()}>
              批量设置渠道
            </Button>
            <span style={{paddingLeft:"12px"}}>当前组合数：{combinList.length}</span>
          </div>
          {combinList.length > 0 ? (
            <VList {...VListProps} />
          ) : (
            <Empty
              style={{ background: '#fff', padding: '24px' }}
              description="暂无数据"
            />
          )}
          {/* <div className={styles.combinCount}>
            当前组合数：{combinList.length}
          </div> */}
        </div>
      </CommonModal>
      {channelSwitch && <BatchSetChannel {...BatchSetChannelProps} />}
      <CommonLoading loading={loading} />
    </div>
  );
};

export default CombinPreview;
